package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.CustomerInfo;
import com.qianying.entity.CustomerMaterial;
import com.qianying.mapper.CustomerInfoMapper;
import com.qianying.mapper.CustomerMaterialMapper;
import com.qianying.service.CustomerInfoService;
import com.qianying.service.CustomerMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户材料Service实现类（优化版）
 * 关联查询客户名称
 */
@Service
public class CustomerMaterialServiceImpl extends ServiceImpl<CustomerMaterialMapper, CustomerMaterial> implements CustomerMaterialService {

    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private CustomerInfoService customerInfoService;

    @Override
    public CommonResult<Page<CustomerMaterial>> getPage(Page<CustomerMaterial> page, String customerName) {
        // 1. 先查询客户材料分页数据
        LambdaQueryWrapper<CustomerMaterial> queryWrapper = new LambdaQueryWrapper<>();

        // 如果传入了客户名称，先查询符合条件的客户ID列表
        List<Long> customerIds = null;
        if (StringUtils.hasText(customerName)) {
            // 查询客户名称模糊匹配的客户ID
            LambdaQueryWrapper<CustomerInfo> customerQuery = new LambdaQueryWrapper<>();
            customerQuery.like(CustomerInfo::getCustomerName, customerName);
            customerIds = customerInfoMapper.selectList(customerQuery).stream()
                    .map(CustomerInfo::getId)
                    .collect(Collectors.toList());

            // 如果没有匹配的客户，直接返回空结果
            if (customerIds == null || customerIds.isEmpty()) {
                return CommonResult.success(new Page<>());
            }

            // 按客户ID筛选材料记录
            queryWrapper.in(CustomerMaterial::getCustomerId, customerIds);
        }

        // 按更新日期倒序
        queryWrapper.orderByDesc(CustomerMaterial::getUpdateTime);

        // 执行分页查询
        Page<CustomerMaterial> materialPage = baseMapper.selectPage(page, queryWrapper);
        List<CustomerMaterial> materialList = materialPage.getRecords();

        // 如果没有数据，直接返回
        if (materialList.isEmpty()) {
            return CommonResult.success(materialPage);
        }

        // 2. 批量查询客户信息（避免N+1查询问题）
        List<Long> ids = materialList.stream()
                .map(CustomerMaterial::getCustomerId)
                .collect(Collectors.toList());

        List<CustomerInfo> customerList = customerInfoMapper.selectBatchIds(ids);

        // 转换为Map便于查询
        Map<Long, String> customerNameMap = customerList.stream()
                .collect(Collectors.toMap(
                        CustomerInfo::getId,
                        CustomerInfo::getCustomerName,
                        (k1, k2) -> k1 // 处理重复ID的情况（理论上不会出现）
                ));

        // 3. 填充客户名称
        materialList.forEach(material -> {
            material.setCustomerName(customerNameMap.get(material.getCustomerId()));
        });

        // 4. 封装结果
        materialPage.setRecords(materialList);
        return CommonResult.success(materialPage);
    }

    @Override
    public CommonResult<CustomerMaterial> getById(Long id) {
        // 1. 查询材料记录
        CustomerMaterial material = baseMapper.selectById(id);
        if (material == null) {
            return CommonResult.failed("未找到ID为" + id + "的记录");
        }

        // 2. 查询关联的客户信息
        CustomerInfo customerInfo = customerInfoMapper.selectById(material.getCustomerId());
        if (customerInfo != null) {
            // 填充客户名称
            material.setCustomerName(customerInfo.getCustomerName());
        } else {
            material.setCustomerName("未知客户（ID：" + material.getCustomerId() + "）");
        }

        return CommonResult.success(material);
    }

    // 其他方法保持不变...
    @Override
    public CommonResult<?> saveMaterial(CustomerMaterial material) {
        if (material.getCustomerId() == null) {
            return CommonResult.failed("客户ID不能为空");
        }
        material.setId(null);
        // 验证客户ID是否存在
        CustomerInfo customer = customerInfoMapper.selectById(material.getCustomerId());
        if (customer == null) {
            return CommonResult.failed("客户ID不存在：" + material.getCustomerId());
        }

        int rows = baseMapper.insert(material);
        return rows > 0 ? CommonResult.success("新增成功") : CommonResult.failed("新增失败");
    }

    @Override
    public CommonResult<?> updateMaterial(CustomerMaterial material) {
        if (material.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }

        // 如果修改了客户ID，验证新客户ID是否存在
        if (material.getCustomerId() != null) {
            CustomerInfo customer = customerInfoMapper.selectById(material.getCustomerId());
            if (customer == null) {
                return CommonResult.failed("客户ID不存在：" + material.getCustomerId());
            }
        }

        int rows = baseMapper.updateById(material);
        return rows > 0 ? CommonResult.success("更新成功") : CommonResult.failed("更新失败，未找到对应记录");
    }

    @Override
    public CommonResult<?> removeById(Long id) {
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        int rows = baseMapper.deleteById(id);
        return rows > 0 ? CommonResult.success("删除成功") : CommonResult.failed("删除失败，未找到对应记录");
    }
}
